import { body, buildCheckFunction } from "express-validator";
import validate from "../middleware/validate";
import { checkEmailExit } from "../model/user";
const crypto = require("crypto");
import express from "express";
import md5 from "../util/md5";



export const validatoRegister = validate([
    // 1. 配置验证规则
    body("email")
        .notEmpty()
        .withMessage("邮箱不能为空")
        // .custom((value, { req }) => {
        //     console.log(req, 'req11111111111111111');

        // }),
        .custom(async (value: string) => {

            // 查询数据库 查看数据是否存在
            const data: string[] = await checkEmailExit(value) as [];
            if (data && data.length) {
                return Promise.reject("此邮箱用户已注册");
            }
        })
])

export const validatoLogin = [
    validate([
        body("email").notEmpty().withMessage("邮箱不能为空"),
        body("password").notEmpty().withMessage("密码不能为空"),
    ]),
    // 验证用户是否存在
    validate([
        body("email").custom(async (value: string, { req }) => {
            console.log('come1111111111');

            const user: any[] = await checkEmailExit(value) as [];
            // 查询数据库查看数据是否存在
            if (!user.length) {
                return Promise.reject("用户不存在");
            }
            const disable = user[0] && user[0].disable;
            if (disable === 0) {
                return Promise.reject("用户已注销,请联系管理员");
            }
            // 将数据挂载到请求对象中，后续的中间件也可以直接使用，就不需要重复查询了
            req.user = user[0];
        }),
    ]),
    // 验证密码是否正确
    validate([
        body("password").custom(async (password, { req }) => {
            if (password !== req.user.password) {
                return Promise.reject("密码错误");
            }
        }),
    ]),

]